package one.stand.controller.home;

import cn.hutool.core.util.StrUtil;
import com.jmp.api.dto.ImContactRequest;
import com.jmp.api.dto.ImInfoResponse;
import com.jmp.api.dto.ImKfResponse;
import com.jmp.autocofiguration.web.interceptor.SecurityAuthCheck;
import com.jmp.base.ChatApi;
import com.jmp.base.MessageApi;
import com.jmp.base.dto.MessagePushRequest;
import com.jmp.base.dto.MessagePushType;
import com.jmp.base.dto.MessageWxSubscribeDto;
import com.jmp.feign.MessageFeign;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import one.stand.advice.ResultEnum;
import one.stand.dto.UserDto;
import one.stand.enums.LoginEnum;
import one.stand.model.BusinessCard;
import one.stand.model.ResultModel;
import one.stand.service.BusinessCardBaseService;
import one.stand.service.user.TokenService;
import one.stand.service.user.UserAdminService;
import one.stand.util.AssertUtil;
import one.stand.util.DateUtil;
import one.stand.util.RequestContext;
import one.stand.util.RequestContextHolder;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@Api(description = "聊天")
@RestController
@RequestMapping("im")
public class ImController {

    @Autowired
    private MessageFeign messageFeign;

    @Autowired
    private BusinessCardBaseService businessCardBaseService;
    @Autowired
    private UserAdminService userAdminService;
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "信息")
    @PostMapping("/info")
    @SecurityAuthCheck
    public ResultModel<ImInfoResponse> info(@RequestAttribute ImContactRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        UserDto user = userAdminService.get(request.getToId());
        ImInfoResponse response = ImInfoResponse.builder()
                .toId(request.getToId())
                .name(Objects.nonNull(user) ? user.getName() : (request.getToId() < 0 ? "客服" : StringUtils.EMPTY))
                .phone(Objects.nonNull(user) ? user.getPhone() : null)
                .myCompanyId(optUser.getCompanyId())
                .build();
        BusinessCard card = businessCardBaseService.getByUserId(request.getToId());
        response.setIsApp(BooleanUtils.toInteger(Objects.nonNull(card)));
        if (Objects.nonNull(card)) {
            response.setPersonalWx(card.getPersonalWx());
            response.setCompanyId(card.getCompanyId());
        }
        return ResultModel.success(response);
    }

    @ApiOperation(value = "客服")
    @GetMapping("/kf")
    @SecurityAuthCheck
    public ResultModel<ImKfResponse> kf() {
        ImKfResponse response = ImKfResponse.builder()
                .kfChatId(ChatApi.CHAT_ID_KF)
                .build();
        return ResultModel.success(response);
    }

    @ApiOperation(value = "联系我")
    @PostMapping("/contact")
    @SecurityAuthCheck
    public ResultModel contact(@RequestAttribute ImContactRequest request) {
        final RequestContext.User optUser = RequestContextHolder.getRequestContext().getUser();
        UserDto user = userAdminService.get(optUser.getUserId());
        AssertUtil.nonNull(user.getPhone(), ResultEnum.FAIL_PHONE_NO);

        BusinessCard card = businessCardBaseService.getByUserId(request.getToId());
        if (Objects.nonNull(card) || tokenService.hasLoginStatus(request.getToId(), LoginEnum.CRM)) {
            MessagePushRequest pushRequest = MessagePushRequest.builder()
                    .type(MessagePushType.IM_CONTACT)
                    .toId(request.getToId())
                    .title(user.getName() + "正在通过花园购与您发起聊天，请尽快回复！")
                    .pageParams(new Object[]{optUser.getUserId(), user.getName()})
                    .build();
            messageFeign.push(pushRequest);
        } else {
            UserDto userModel = userAdminService.get(optUser.getUserId());
            String[] arr = {StrUtil.subSufByLength(userModel.getName(), 10), DateUtil.getDay(), "点击进入开始于客户聊天"};
            MessageWxSubscribeDto messageDto = MessageWxSubscribeDto.builder()
                    .type(MessageApi.MSG_UNREAD)
                    .toId(request.getToId())
                    .pageArr(new String[]{String.valueOf(optUser.getUserId())})
                    .dataArr(arr)
                    .build();
            messageFeign.wxSubscribe(messageDto);
        }

        return ResultModel.success();
    }
}
